from fastapi import APIRouter
from fastapi.encoders import jsonable_encoder
from models.Models import Content, ArticleCategory
from db.DBUtil import DBUtil
from utils.result_back import success, fail

router = APIRouter()


@router.get("/list/{page_index}/{page_size}")
def list_content(page_index: int, page_size: int):
    db_util = DBUtil()
    session = db_util.get_session()
    contents = session.query(Content).order_by(Content.id.desc()).limit(page_size).offset(
        (page_index - 1) * page_size).all()
    count = session.query(Content).count()
    db_util.close()
    result = {
        'records': contents,
        'total': count,
        'current': page_index
    }
    return success(result)


@router.get("/load/{content_id}")
def load_content(content_id: int):
    db_util = DBUtil()
    session = db_util.get_session()
    content = session.query(Content, ArticleCategory).join(ArticleCategory, Content.category_code == ArticleCategory.code).filter(Content.id == content_id).first()
    db_util.close()
    return success(content)
